package maputil

import (
	"io"
	"log/slog"
	"os"
	"runtime"

	"github.com/qedus/osmpbf"
)

type PbfData struct {
	Nodes []*osmpbf.Node
	Ways  []*osmpbf.Way
}

// Parse 从指定路径解析OSM PBF文件，返回道路网络数据
func ParseWayFromPbf(pbf string) (*PbfData, error) {
	// 打开PBF文件
	f, err := os.Open(pbf)
	if err != nil {
		slog.Error("打开文件失败...", "error", err)
		return nil, err
	}
	defer f.Close()

	// 创建PBF解码器
	d := osmpbf.NewDecoder(f)
	d.SetBufferSize(osmpbf.MaxBlobSize)

	// 开始解码过程
	if err := d.Start(runtime.GOMAXPROCS(-1)); err != nil {
		slog.Error("启动解码器失败...", "error", err)
		return nil, err
	}

	var nodes []*osmpbf.Node
	var ways []*osmpbf.Way

	// 迭代处理OSM元素
	for {
		if v, err := d.Decode(); err == io.EOF {
			break
		} else if err != nil {
			slog.Error("解码错误...", "error", err)
			return nil, err
		} else {
			switch obj := v.(type) {
			case *osmpbf.Node:
				nodes = append(nodes, obj)
			case *osmpbf.Way:
				if isRoadWay(obj) {
					ways = append(ways, obj)
				}
			}
		}
	}

	slog.Info("解析完成...", "节点", len(nodes), "道路", len(ways))
	return &PbfData{
		Nodes: nodes,
		Ways:  ways,
	}, nil
}

// isRoadWay 判断是否为道路类型的路径
func isRoadWay(w *osmpbf.Way) bool {
	_, exists := w.Tags["highway"]
	return exists
}
